// 2023/7/28 Adam
#pragma once

#include <stdio.h>
#include <stdint.h>
#include <string>
#include <sstream>
#include "rc.h"
#include "sql/parser/parse_defs.h"

inline int str_to_num(const char* str)
{
    int len = strlen(str);
    int q = 1;  // 步长
    int ans = 0;
    for(int i = len - 1; i >= 0; i--){
        ans += (str[i] - '0') * q;
        q *= 10;
    }
    return ans;
}

// leap_year return True else False
inline bool is_leap_year(int year)
{
    return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0);
}

inline bool check_date(int year, int month, int day)
{
    // check validate
    if(year < 1970 || year > 2038 
    || month < 1 || month >12 
    || day < 1 || day >31){
        return false;
    }

    if(year == 2038 && month > 2){
        return false;
    }

    if(year == 1970 && month > 1 && day > 1){
        return false;
    }

    int max_day_in_month[2][13]={{0,31,28,31,30,31,30,31,31,30,31,30,31},
                                {0,31,29,31,30,31,30,31,31,30,31,30,31}};
    
    const int max_day = max_day_in_month[is_leap_year(year)][month];

    // check validate
    if(day > max_day){
        return false;
    }

    return true;
}

inline RC string2date(char *str, int32_t &date)
{
    int year = 0;
    int month = 0;
    int day = 0;
    int ret = sscanf(str,"%d-%d-%d",&year,&month,&day);
    if(ret != 3){
        return RC::INVALID_ARGUMENT;
    }

    // check validate
    bool b = check_date(year, month, day);

    // translate string to int
    //0000-00-00
    if(!b){
        return RC::INVALID_ARGUMENT;
    }
    
    date = day + month*100 + year*10000;
    return RC::SUCCESS;

}

inline std::string date2string(int32_t date)
{
    int y, m, d;
    y = date/10000;
    m = (date - y*10000)/100;
    d = date % 100;
    std::stringstream year,month,day;
    year << y;
    month << m;
    day << d;
    std::string s = year.str() + '-';
    if(m < 10){
        s += '0' + month.str() + '-';
    }else{
        s += month.str() + '-';
    }
    if(d < 10){
        s += '0' + day.str();
    }else{
        s += day.str();
    }
    return s;
}